package features.advance.jdk.agent;

import com.sun.tools.attach.VirtualMachine;
import com.sun.tools.attach.VirtualMachineDescriptor;

import java.lang.instrument.Instrumentation;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;

/**
 * @author LIN
 * @date 2022-05-04 22:30
 *
 * VirtualMachine在jdk的tools.jar包里
 */
public class Demo {
    public static void premain(String args,  Instrumentation inst){
        System.out.println("premain start");
        System.out.println(args);
    }

    public static void agentmain(String args,  Instrumentation inst){
        System.out.println("loadagent after main run.args="+args);
        Class[] loadedClasses = inst.getAllLoadedClasses();
        for (Class loadedClass : loadedClasses) {
            System.out.println(loadedClass.getName());
        }
        System.out.println("agent run completely.");
    }


    public static void main(String[] args) {

        Properties properties = System.getProperties();
        Enumeration<?> enumeration = properties.propertyNames();
        while (enumeration.hasMoreElements()){
            Object o = enumeration.nextElement();
//            if("java.ext.dirs".equals(o)){
//                properties.setProperty((String) o,
//                properties.getProperty((String)o)+";"+
//                "C:\\Program Files\\Java\\jdk1.8.0_291\\lib\\tools.jar;");
//            }
            System.out.println(o+"="+properties.getProperty((String)o));
        }

        List<VirtualMachineDescriptor> list = VirtualMachine.list();
        list.forEach(e->{
            String id = e.id();
            try{
                VirtualMachine attach = VirtualMachine.attach(id);
                System.out.println(attach.getAgentProperties());
            }catch(Exception e1){
                e1.printStackTrace();
            }
                    });
        try{

            String[] var = new String[0];
//            JStack.main(var);
        }catch(Exception e){
            e.printStackTrace();
        }

    }


}
